//
//  File.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/26.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import Foundation


extension LGTRWZPostVC{
    
    //视图添加
    func setUIAdd(){
        self.setBavBarStyle(navBarHiden: false, title: "发布任务", back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH, width: Double(KScreenW), height: Double(KScreenH) - NavBarH - TabBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self as UITableViewDelegate
        self.tableView?.dataSource = self as UITableViewDataSource
        self.tableView?.register(LGTRWZPostInputCell.classForCoder(), forCellReuseIdentifier: "inputCell")
        self.tableView?.register(LGTRWZPostSelectCell.classForCoder(), forCellReuseIdentifier: "selectCell")
        self.tableView?.register(LGTRWZPostTypeCell.classForCoder(), forCellReuseIdentifier: "typeCell")
        self.tableView?.register(LGTRWZPostOptionCell.classForCoder(), forCellReuseIdentifier: "optionCell")
        self.tableView?.register(LGTRWZPostPayCell.classForCoder(), forCellReuseIdentifier: "payCell")
        self.tableView?.register(LGTRWZPostAddStepCell.classForCoder(), forCellReuseIdentifier: "addStepCell")
        self.tableView?.register(LGTRWZPostRulerCell.classForCoder(), forCellReuseIdentifier: "rulerCell")
        self.tableView?.register(LGTRWZUrlStepCell.classForCoder(), forCellReuseIdentifier: "urlCell")
        self.tableView?.register(LGTRWZQRStepCell.classForCoder(), forCellReuseIdentifier: "qrcell")
        self.tableView?.register(LGTRWZCopyStepCell.classForCoder(), forCellReuseIdentifier: "copyCell")
        self.tableView?.register(LGTRWZImageTextStepCell.classForCoder(), forCellReuseIdentifier: "imagetextcell")
        self.tableView?.register(LGTStepTitleViewCell.classForCoder(), forCellReuseIdentifier: "stepHeadCell")
        
        self.tableView?.estimatedRowHeight = 40
        self.tableView?.rowHeight = UITableView.automaticDimension
        //tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: -SizeFitFloat(8), right: 0)
        
        //preview  applicationforissuance
        let previewBtn:UIButton = LGTViewCreateUtil.share.createButtonTitleAndImage(imageName: "preview", title: "预览", color:TextColor, font: Font_Normal_18, backColor: UIColor.white)
        self.view.addSubview(previewBtn)
        previewBtn.tag = 0
        previewBtn.snp.makeConstraints { (make) in
            make.bottom.left.equalTo(0)
            make.height.equalTo(TabBarH)
            make.width.equalTo(SizeFit(116))
        }
        previewBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)
        
        let postBtn:UIButton = LGTViewCreateUtil.share.createButtonTitleAndImage(imageName: "applicationforissuance", title: "申请发布", color:UIColor.white, font: Font_Normal_18, backColor: YellowColor)
        self.view.addSubview(postBtn)
        postBtn.tag = 1
        postBtn.snp.makeConstraints { (make) in
            make.bottom.right.equalTo(0)
            make.left.equalTo(previewBtn.snp_rightMargin)
            make.height.equalTo(TabBarH)
        }
        postBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)
    }
    
    @objc func postAction(sender:UIButton){
        
        if sender.tag == 0{
            let vc:LGTPostDetailVC = LGTPostDetailVC()
            vc.modalPresentationStyle = .overCurrentContext
            var submit:Dictionary<String, Any?> = self.submitDataInfo2
            submit["step"] = self.stepArray
            vc.submitDataInfo2 = submit
            self.navigationController?.present(vc, animated: true, completion: nil)
            return
        }
        
        //User_Account_URL
        let payVC:LGTRWZPayVC = LGTRWZPayVC()
        payVC.modalPresentationStyle = .overCurrentContext
        var submit:Dictionary<String, Any?> = self.submitDataInfo2
        submit["step"] = self.stepArray
        payVC.submitDataInfo = submit
        self.navigationController?.present(payVC, animated: false, completion: nil)
    }
    
    
    //获取参数
    func getData(){
        //初始化数据
        self.submitDataInfo2 = rwz_getSubmitInfo()
        self.stepArray = self.submitDataInfo2["step"] as? Array<Dictionary<String, Any?>> ?? []
        
        //发布参数获取
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Post_Param_URL, param: [:], success: { (json) in
            weakSelf?.postParamModel = try! lgtDecode(PostParamModel.self, param: (json["data"] as! [String : Any]))
            weakSelf?.initData()
            weakSelf?.alerViewAction()
        }) { (json) in
            weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text)
        }
    }
    
    func alerViewAction(){
        //            var is_tip:Int? = 0  // 是否提示  1 可以
        //            var is_post:Int? = 0 // 是否可以发布  1 可以
        //            var message:String? = ""  //发布说明
        if self.postParamModel?.post_limit?.is_tip == 1{
            //弹窗
            weak var weakSelf = self
            LGTRWZCommenAlert.CommenAlertalertShow(title: "温馨提示", desc: self.postParamModel?.post_limit?.message ?? "", sureTitle: "联系客服", cancelTitle: "取消",  sureBlock: {
                //联系客服待处理
//                if weakSelf?.postParamModel?.post_limit?.is_post == 1{
//
//                }else{
//
//                }
            }, cancelBlock: {
                if weakSelf?.postParamModel?.post_limit?.is_post == 0{
                    weakSelf?.navigationController?.popViewController(animated: true)
                }
                
            }, sureCloseState:false,
                currentVC: self.navigationController!)
        }
    }
    
    //初始化数据
    func initData(reload:Bool=true){
        let workTime:String = (self.submitDataInfo2["workTime"] as? PostNameModel)?.name ?? ""
        let reviewTime:String = (self.submitDataInfo2["reviewTime"] as? PostNameModel)?.name ?? ""
        let workTimes:String = (self.submitDataInfo2["workTimes"] as? PostNameModel)?.name ?? ""
        let offline:String = self.submitDataInfo2["offline"]  as? String ?? ""
        let typeModel = self.submitDataInfo2["type"] ?? nil
        let os = self.submitDataInfo2["os"] ?? nil
        let projectName = self.submitDataInfo2["projectName"] as? String ?? ""
        let taskRequest = self.submitDataInfo2["taskRequest"] as? String ?? ""
        
        var taskPriceText = self.submitDataInfo2["workPrice"] as? String ?? ""
        var taskPriceTextDesc = ""
        var taskCountText = self.submitDataInfo2["taskCount"] as? String ?? ""
        var taskCountTextDesc = ""
        
        if typeModel != nil{
            let minPrice:Double = Double((typeModel as! PostNameModel).min_price ?? 0)
            taskPriceTextDesc = "最低限价\(minPrice / 100.0)元/单"
            taskCountTextDesc = "最低\((typeModel as! PostNameModel).min_count ?? 0)单"
        }
        
        //置顶费用
        let topTimeMoney:Int = self.postParamModel?.top_price ?? 0
        let topTime:Int = Int(self.submitDataInfo2["toptime"] as? String ?? "") ?? 0
        let topTotalMoney:Double = Double(topTime * topTimeMoney) / 100.0
        let topMonyStr:String = "\(topTotalMoney)元"
        let topTimeStr:String = topTime == 0 ? "" : "\(topTime)"
        self.submitDataInfo2["topPrice"] = topTotalMoney
        
        //保证金占比 任务费1 服务费
        let commission_rate:CGFloat = self.postParamModel?.commission_rate ?? 0.0
        let deposit_rate:CGFloat = self.postParamModel?.deposit_rate ?? 0.0
        let rate:Double = (100.0 + Double(commission_rate) + Double(deposit_rate)) / 100.0
        let workPrice = Double(self.submitDataInfo2["workPrice"] as? String ?? "") ?? 0.0
        let taskCount:Double = Double(self.submitDataInfo2["taskCount"] as? String ?? "") ?? 0.0
        let taskMoney = workPrice * taskCount * rate
        let payMoney:Double = taskMoney + topTotalMoney
        self.submitDataInfo2["payMoney"] = payMoney
        let payStr:String = "\(payMoney)元"
        
        self.data = [
            [["title": "请选择类型", "typeSelect":true, "array":self.postParamModel?.type_list ?? Array.init(), "type": typeModel]],
            [["title": "支持设备", "typeSelect":true, "array":self.postParamModel?.os_list ?? Array.init(),
              "type": os]],
            [
                ["title": "项目名称", "input":true, "placehoder":"请输入15个字以内标题", "limit":15, "textFieldText":projectName],
                ["title": "任务要求", "input":true, "placehoder":"可输入200个字以内", "limit":200, "textFieldText":taskRequest],
                ["title": "做单时间", "subText":workTime],
                ["title": "审核时间", "subText":reviewTime],
                ["title": "做单次数", "subText":workTimes]
            ],
            
//        var taskPriceText = self.submitDataInfo2["workPrice"] as? String ?? ""
//        var taskPriceTextDesc = ""
//        var taskCountText = self.submitDataInfo2["taskCount"] as? String ?? ""
//        var taskCountTextDesc = ""
            
            [["title": "任务单价", "input":true, "placehoder":taskPriceTextDesc, "limit":-1, "keyboard":UIKeyboardType.decimalPad, "type": typeModel, "isTaskPrice":true, "textFieldText":taskPriceText],
             ["title": "任务数量", "input":true, "placehoder":taskCountTextDesc, "limit":-1, "keyboard":UIKeyboardType.numberPad, "type": typeModel, "isTaskCount":true, "textFieldText":taskCountText]
            ],
            [["option":true, "toptime":topTimeStr, "topTotalMoney": topMonyStr, "topTimeMoney":topTimeMoney],  //可选
                ["title": "下线时间", "subText":offline]
            ],
            [["pay":true, "payStr":payStr, "commission_rate": commission_rate, "deposit_rate":deposit_rate],  //需支付的视图
            ],
            [["title":"添加步骤", "addStep":true],
             ["ruler":true]
            ]
        ]
        
        if self.stepArray.count > 0{
            var stepArray = self.stepArray
            stepArray.insert(["stepHead": true], at: 0)
            self.data.insert(stepArray, at: self.data.count - 1)
        }
        
        //是否需要刷新数据
        if reload == true{
            self.tableView?.reloadData()
        }
    }
    
    
    //显示弹窗 添加步骤
    func showStepView(view:UIView){
        if self.addStepView == nil{
            let h:CGFloat = SizeFitFloat(35)
            let w:CGFloat = SizeFitFloat(134)
            let top:CGFloat = SizeFitFloat(5)
            self.addStepView = LGTViewCreateUtil.share.createImageViewCorner(corner: SizeFitFloat(5))
            self.addStepView?.isUserInteractionEnabled = true
            self.addStepView?.backgroundColor = YellowColor
            self.view.addSubview(self.addStepView!)
            self.addStepView!.snp.makeConstraints({ (make) in
                make.height.equalTo(SizeFit(220))
                make.bottom.equalTo(0)
                make.width.equalTo(w)
                make.right.equalTo(SizeFit(-12))
            })
            
            let data:Array<Dictionary<String, Any>> = [["icon":"enterwebsite", "title":"输入网址"],
                                                       ["icon":"orcode", "title":"二维码"],
                                                       ["icon":"duplicatedata", "title":"复制数据"],
                                                       ["icon":"illustration", "title":"图文说明"],
                                                       ["icon":"verificationdiagram", "title":"验证图"],
                                                       ["icon":"collectinformation", "title":"收集信息"]
            ]
            
            for i in 0..<data.count{
                let button:UIButton = UIButton.init()
                self.addStepView?.addSubview(button)
                button.snp.makeConstraints { (make) in
                    make.top.equalTo(top + h * CGFloat(i))
                    make.width.equalTo(w)
                    make.left.equalTo(0)
                    make.height.equalTo(h)
                }
                button.tag = i
                button.addTarget(self, action: #selector(selectStepAction), for: UIControl.Event.touchUpInside)
                
                let info:Dictionary<String, Any> = data[i]
                let icon:String = info["icon"] as! String
                let iconImage:UIImageView = LGTViewCreateUtil.share.createImageView(image: icon)
                self.addStepView!.addSubview(iconImage)
                iconImage.snp.makeConstraints { (make) in
                    make.left.equalTo(SizeFit(18))
                    make.width.height.equalTo(SizeFit(17))
                    make.centerY.equalTo(button)
                }
                
                let title:String = info["title"] as! String
                let label:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: UIColor.white, fontSize: SizeFitFloat(16), text: title)
                self.addStepView!.addSubview(label)
                label.snp.makeConstraints { (make) in
                    make.left.equalTo(iconImage.snp_rightMargin).offset(SizeFitFloat(12))
                    make.height.equalTo(SizeFit(16))
                    make.centerY.equalTo(button)
                }
                
            }
        }
        
        self.addStepView?.isHidden = false
        //view  在tableView的frame
        let rect:CGRect = self.tableView!.convert(view.frame, from: view.superview)
        let contentOffset = self.tableView!.contentOffset
        
        let offsetY = contentOffset.y
        let min = rect.minY
        let max = rect.maxY
        let minDis = min - offsetY
        let maxDis = max - offsetY
        let hAndSpace = SizeFitFloat(220 + 13)
        
        //可以显示
        if minDis >= hAndSpace{
            let bottom = KScreenH - CGFloat(NavBarH) - minDis + SizeFitFloat(13)
            print("上方")
            self.addStepView!.snp.updateConstraints { (make) in
                make.bottom.equalTo(-bottom)
            }
        }else{
            print("下方")
            let bottom = KScreenH - maxDis - CGFloat(NavBarH) - hAndSpace
            self.addStepView!.snp.updateConstraints { (make) in
                make.bottom.equalTo(-bottom)
            }
        }
    }
    
    //选择添加到步骤
    @objc func selectStepAction(sender:UIButton){
        self.addStepView!.isHidden = true
        let index:Int = sender.tag
        self.gotoStepDetailVC(index: index)
    }
    
    //跳转详情
    func gotoStepDetailVC(index:Int, info:Dictionary<String, Any>?=nil){
        //收集信息
        if index == 5{
            let vc:LGTPostCollectionStepVC =  LGTPostCollectionStepVC()
            vc.modalPresentationStyle = .overCurrentContext
            vc.clickInfoBlock = self.stepInfoSaveBlock
            vc.index = index
            vc.info = info
            self.navigationController!.present(vc, animated: false, completion: nil)
            return
        }
        
        let key = "\(index)"
        //图片
        if index == 1 || index == 3 || index == 4{
            //LGTPostUploadImageStepVC type 0上传验证图  1上传说明图 2上传二维码
            let dictInfo = ["1" : 2,
                            "3" : 1,
                            "4" : 0]
            let type = dictInfo[key]
            let vc:LGTPostUploadImageStepVC =  LGTPostUploadImageStepVC()
            vc.modalPresentationStyle = .overCurrentContext
            self.navigationController!.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
            vc.type = type ?? 0
            vc.index = index
            vc.info = info
            vc.clickInfoBlock = self.stepInfoSaveBlock
            self.navigationController!.present(vc, animated: false, completion: nil)
            return
        }
        
        //LGTPostUrlStepVC type 0复制数据  1输入网址
        let typeInfo = ["0" : 1,
                    "2" : 0]
        let type = typeInfo[key]
        let vc:LGTPostUrlStepVC =  LGTPostUrlStepVC()
        vc.type = type ?? 0
        vc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
        vc.clickInfoBlock = self.stepInfoSaveBlock
        vc.index = index
        vc.info = info
        self.navigationController!.present(vc, animated: false, completion: nil)
    }
}
